'use client';

import React, { useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Users, Pickaxe, Coins, DollarSign, Target, TrendingUp } from 'lucide-react';
import { multiChainApi } from '@/lib/multi-chain-api';
import { API_ENDPOINTS } from '@/config/api';
import { formatNumber, formatCurrency } from '@/lib/utils';
import { StatsChart } from '@/components/dashboard/stats-chart';
import { RecentActivity } from '@/components/dashboard/recent-activity';
import { SyncStatusOverview } from '@/components/dashboard/SyncStatusOverview';
import { usePermissions } from '@/hooks/usePermissions';
import { useAuthStore } from '@/store/auth';
import { useChain } from '@/context/ChainContext';
import NetworkSwitcher from '@/components/layout/NetworkSwitcher';
import { debugApiCall } from '@/lib/api-debug';
import { useTranslation } from 'react-i18next';

interface SystemStats {
  total_users: number;
  active_users: number;
  total_miners: number;
  active_miners: number;
  total_staked: number;
  total_rewards_distributed: number;
  total_pos: number;
  total_pop: number;
}

export default function DashboardPage() {
  const { t } = useTranslation('dashboard');
  const { getAdminForChain } = useAuthStore();
  const { currentChain } = useChain();
  const { userRole, permissions, isSuperAdmin } = usePermissions();
  
  const admin = getAdminForChain(currentChain);
  
  // Debug API connection on component mount
  // useEffect(() => {
  //   if (typeof window !== 'undefined') {
  //     debugApiCall();
  //   }
  // }, []);
  
  const { data: stats, isLoading: statsLoading } = useQuery<SystemStats>({
    queryKey: ['system-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.admin.stats);
      return response.data;
    },
  });

  const statCards = [
    {
      title: t('stats.totalUsers'),
      value: stats?.total_users || 0,
      icon: Users,
      change: '+12.5%',
      color: 'text-blue-600',
      bgColor: 'bg-blue-100',
    },
    {
      title: t('stats.activeMiners'),
      value: stats?.active_miners || 0,
      icon: Pickaxe,
      change: '+8.3%',
      color: 'text-green-600',
      bgColor: 'bg-green-100',
    },
    {
      title: t('stats.totalStaked'),
      value: formatCurrency(stats?.total_staked || 0),
      icon: Coins,
      change: '+15.2%',
      color: 'text-purple-600',
      bgColor: 'bg-purple-100',
    },
    {
      title: t('stats.dailyRewards'),
      value: formatCurrency(stats?.total_rewards_distributed || 0),
      icon: DollarSign,
      change: '+5.7%',
      color: 'text-orange-600',
      bgColor: 'bg-orange-100',
    },
    {
      title: '全网POS总量',
      value: formatNumber(stats?.total_pos || 0),
      icon: Target,
      change: '+3.2%',
      color: 'text-indigo-600',
      bgColor: 'bg-indigo-100',
    },
    {
      title: '全网POP总量',
      value: formatNumber(stats?.total_pop || 0),
      icon: TrendingUp,
      change: '+4.1%',
      color: 'text-emerald-600',
      bgColor: 'bg-emerald-100',
    },
  ];

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
          {/* Page Header */}
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{t('title')}</h1>
            <p className="text-gray-500">{t('subtitle')}</p>
          </div>
          
          {/* Network Switcher */}
          <NetworkSwitcher />
          
          {/* Stats Grid */}
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
            {statCards.map((stat) => {
              const Icon = stat.icon;
              return (
                <Card key={stat.title}>
                  <CardContent className="p-6">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium text-gray-500">{stat.title}</p>
                        <p className="mt-2 text-3xl font-bold text-gray-900">
                          {typeof stat.value === 'string' ? stat.value : formatNumber(stat.value)}
                        </p>
                        <p className="mt-2 text-sm text-green-600">{stat.change}</p>
                      </div>
                      <div className={`rounded-lg p-3 ${stat.bgColor}`}>
                        <Icon className={`h-6 w-6 ${stat.color}`} />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
          
          {/* Charts and Activity */}
          <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
            {/* Main Chart */}
            <div className="lg:col-span-2">
              <Card>
                <CardHeader>
                  <CardTitle>每日新增POP/POS数量</CardTitle>
                </CardHeader>
                <CardContent>
                  <StatsChart />
                </CardContent>
              </Card>
            </div>
            
            {/* Recent Activity */}
            <div>
              <Card>
                <CardHeader>
                  <CardTitle>{t('recentActivity.title')}</CardTitle>
                </CardHeader>
                <CardContent>
                  <RecentActivity />
                </CardContent>
              </Card>
            </div>
          </div>
          
          {/* Blockchain Sync Status */}
          <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
            <SyncStatusOverview />
            
            {/* Additional Status Card */}
            <Card>
              <CardHeader>
                <CardTitle>{t('systemStatus.title')}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">{t('systemStatus.database')}</span>
                  <div className="flex items-center gap-2 text-green-600">
                    <div className="w-2 h-2 bg-green-500 rounded-full" />
                    <span className="text-sm">{t('systemStatus.operational')}</span>
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">{t('systemStatus.api')}</span>
                  <span className="text-sm font-medium">{'< 100ms'}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">{t('systemStatus.cache')}</span>
                  <span className="text-sm font-medium text-green-600">{t('systemStatus.operational')}</span>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}